//
// Created by lxx on 2022/1/6.
//
#include "CloudLoader.h"
#include <algorithm/rayTracing/qmcrt_util/check_cuda.h>
#include <algorithm/rayTracing/qmcrt_util/destroy.h>
#include <algorithm/rayTracing/qmcrt_util/global_function.cuh>

#include <fstream>
#include <iostream>

using namespace std;
using namespace solar;

CloudLoader* CloudLoader::cloudLoaders;

auto CloudLoader::getInstance() -> CloudLoader*
{
    if (cloudLoaders == nullptr)
    {
        cloudLoaders = new CloudLoader();
    }
    return cloudLoaders;
}

auto CloudLoader::loadCloudMap(std::string cloud_file_path) -> int
{

    ifstream infile(cloud_file_path, std::ios::in);
    float height = 0.0;
    infile >> x_size >> y_size;
    //    infile>>start_point.x>>start_point.y>>start_point.z;
    infile >> height;

    cloudMap = new float[x_size * y_size];
    int i = 0;
    while (!infile.eof())
    {
        infile >> cloudMap[i++];
    }
    /*    for(int i=0;i<10;i++){
            printf("%f  ",cloudMap[i]);
        }
        printf("\n");
        for(int i=0;i<10;i++){
            printf("%f  ",cloudMap[i*5000]);
        }
        printf("\n");*/

    pixel = 1.0f;
    start_point.x = -x_size * pixel / 2.0f; // local coordinate
    start_point.z = -y_size * pixel / 2.0f; // local coordinate
    start_point.y = 1000;
    checkCudaErrors(cudaMalloc((void**)&d_cloudMap, sizeof(float) * x_size * y_size));
    global_func::cpu2gpu(d_cloudMap, cloudMap, x_size * y_size);
    bound_NW = make_float2(start_point.x, start_point.z);
    bound_NE = make_float2(start_point.x + x_size, start_point.z);
    bound_SW = make_float2(start_point.x, start_point.z + y_size);
    bound_SE = make_float2(start_point.x + x_size, start_point.z + y_size);
    return 1;
}
CloudLoader::~CloudLoader()
{
    clear();
    cloudLoaders = nullptr;
}

auto CloudLoader::clear() -> bool
{
    // 1. Free memory on GPU

    //    checkCudaErrors(cudaFree(d_cloudMap));
    //    d_cloudMap = nullptr;
    // 2. Free memory on CPU
    //    free_scene::cpu_free(cloudMap);
    return true;
}
